package com.yearner.reviewplan.common.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.concurrent.Executor;

/**
 * @author pengyg
 * @since 2020/3/3
 */
@Component
public class AsyncWorker {
    @Autowired
    @Qualifier(value = "myTasks")
    private Executor asyncTask;

    private LinkedList<Runnable> todoList = new LinkedList<>();

    public void addTask(Runnable command) {
        this.todoList.add(command);
    }

    @Scheduled(fixedDelay = 60000, initialDelay = 6000)
    public void scheduledExecute() {
        if (!todoList.isEmpty()) {
            Iterator<Runnable> iterator = todoList.iterator();
            while (iterator.hasNext()) {
                Runnable next = iterator.next();
                if (next != null) {
                    asyncTask.execute(next);
                }
                iterator.remove();
            }
        }
    }
}
